<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Combined Pagination</title>
</head>

<body>
    <div id="app">
        <page :total-time="100" :item-per-page="10" @page-change="onPageChange"></page>
        <ul>
            <!-- 页面 -->
            <li v-for="item in pageData" :key="item">{{ item }}</li>
        </ul>


        <l-page :total-items="100" :items-per-page="10" @page-change="onPageChange"></l-page>
    </div>
</body>
<script src="./vue.js"></script>
<script>
    const { ref, createApp, computed } = Vue;

    const app = createApp({
        setup() {
            const totalItems = 20;      //控制页面中li的数量
            const itemsPerPage = 2;     //一次输出多少个li
            const page = ref(1)
            // 根据总数据条数和每页数据条数计算总页数
            const totalPages = computed(() => Math.ceil(totalItems / itemsPerPage));

            // 计算当前页要显示的数据
            const pageData = computed(() => {
                const startIndex = (page.value - 1) * itemsPerPage;
                const endIndex = startIndex + itemsPerPage;

                // 卡住了，
                return Array.from({ length: totalItems }, (_, index) => index + 1).slice(startIndex, endIndex);
            });


            // 更新当前页码并
            const onPageChange = (newPage) => {
                page.value = newPage;
                console.log(`当前页码：${newPage}`);
            }

            return {
                totalItems,
                itemsPerPage,
                pageData,
                onPageChange,
                page,
                totalPages
            };
        },
    });

    app.component('l-page', {
        props: ['totalItems', 'itemsPerPage'],


        // 不太懂    声明组件触发的事件为 page-change?
        emits: ['page-change'],


        setup(props, { emit }) {
            let currentPage = ref(1);
            const totalPages = computed(() => Math.ceil(props.totalItems / props.itemsPerPage));

            //    上一页
            const prevPage = () => {
                if (currentPage.value > 1) {
                    currentPage.value--;
                    emit('page-change', currentPage.value);
                }
            }
            const nextPage = () => {
                if (currentPage.value < totalPages.value) {
                    currentPage.value++;
                    emit('page-change', currentPage.value);
                }
            };
            return {
                currentPage,
                totalPages,
                prevPage,
                nextPage
            };
        },
        template: `
      <div>
        <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
        <span>{{ currentPage }} / {{ totalPages }}</span>
        <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
      </div>
    `
    });

    app.mount("#app");
</script>

</html>